package com.onenine.chat.rongcloud;

import android.content.Context;

import com.onenine.app.request.TokenRequest;
import com.onenine.app.response.TokenResponse;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.common.util.Logger;

import java.util.Objects;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.ErrorCode;

/**
 * 创建时间：2018/5/28 0028 17:13
 * 创建人：fly
 * 功能描述：融云连接管理
 */
public class RcConnector {

    private static final int TOKEN_INVALID = -4;    //token不正确或过期了
    private static final int TOKEN_UNAVAILABLE = -5;//token未获取成功
    private static final int MAX_TOKEN_GET_COUNT = 3;
    private static String mUserId;
    private static int mTokenFailCount;
    private static boolean isInit;
    private static boolean isConnected;

    public interface OnConnectStatusListener {
        void onSuccess(String userId, String token);

        void onFailure(ErrorCode errorCode);
    }

    public interface OnGetTokenListener {
        void onSuccess(String token);

        void onFailure(String errorMsg);
    }

    private RcConnector() {
    }

    /**
     * 初始化sdk
     *
     * @param context
     */
    public static void initialize(Context context) {
        isInit = true;
        RongIMClient.init(context);
    }

    /**
     * 初始化sdk
     *
     * @param context
     * @param appKey
     */
    public static void initialize(Context context, String appKey) {
        isInit = true;
        RongIMClient.init(context, appKey);
    }

    /**
     * 获取token
     *
     * @param userId
     * @param onGetTokenListener
     */
    public static void getToken(String userId, final OnGetTokenListener onGetTokenListener) {
        Objects.requireNonNull(userId, "userId is null");
        mUserId = userId;
        OkRequest.getInstance().withUrl(UrlConfig.GET_TOKEN).withRequest(new TokenRequest(userId)).doRequest(
                RcConnector.class.getSimpleName(), new OkCallback<TokenResponse>() {
                    @Override
                    public void onResponse(TokenResponse tokenResponse, String srcData) {
                        if (onGetTokenListener != null) {
                            if (tokenResponse.isSuccess()) {
                                onGetTokenListener.onSuccess(tokenResponse.getToken());
                            } else {
                                onGetTokenListener.onFailure(tokenResponse.getMessage());
                            }
                        }
                    }
                });
    }

    /**
     * 获取token并自动连接
     *
     * @param userId
     * @param connectStatusListener
     */
    public static void getTokenAndConnect(String userId, final OnConnectStatusListener connectStatusListener) {
        mUserId = userId;
        getToken(userId, new OnGetTokenListener() {
            @Override
            public void onSuccess(String token) {
                connect(token, connectStatusListener);
            }

            @Override
            public void onFailure(String errorMsg) {
                connectStatusListener.onFailure(ErrorCode.valueOf(TOKEN_UNAVAILABLE));
            }
        });
    }

    /**
     * 连接sdk服务器
     */
    public static void connect(String token, OnConnectStatusListener listener) {
        if (!isInit) {
            Logger.e("未初始化");
            return;
        }
        Objects.requireNonNull(token, "token不能为空");
        doConnect(token, listener);
    }

    /**
     * 执行连接sdk服务器
     */
    private static void doConnect(final String token, final OnConnectStatusListener listener) {
        RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                //token无效或过期了，一般要重新获取新的token
                //默认重复3次请求token
                Logger.e("连接融云服务器失败，尝试重连");
                if (++mTokenFailCount < MAX_TOKEN_GET_COUNT) {
                    getTokenAndConnect(mUserId, listener);
                } else {
                    mTokenFailCount = 0;
                    isConnected = false;
                    if (listener != null) {
                        listener.onFailure(ErrorCode.valueOf(TOKEN_INVALID));
                    }
                }
            }

            @Override
            public void onSuccess(String userId) {
                mTokenFailCount = 0;
                isConnected = true;
                Logger.e("连接融云服务器成功");
                if (listener != null) {
                    listener.onSuccess(userId, token);
                }
            }

            @Override
            public void onError(ErrorCode errorCode) {
                isConnected = false;
                Logger.e("连接融云服务器失败:" + errorCode.getValue());
                if (listener != null) {
                    listener.onFailure(errorCode);
                }
            }
        });
    }

    /**
     * 断开连接
     */
    public static void disconnect() {
        if (!isInit) {
            Logger.e("未初始化");
            return;
        }
        isConnected = false;
        RongIMClient.getInstance().disconnect();
    }

    /**
     * 退出登录
     */
    public static void logout() {
        if (!isInit) {
            Logger.e("未初始化");
            return;
        }
        isConnected = false;
        RongIMClient.getInstance().logout();
    }

    /**
     * 设置连接状态监听
     */
    public static void setConnectStatusListener(RongIMClient.ConnectionStatusListener connectStatusListener) {
        RongIMClient.setConnectionStatusListener(connectStatusListener);
    }

    /**
     * 融云服务器是否连接成功
     *
     * @return
     */
    public static boolean isConnected() {
        return isConnected;
    }

}
